package yxy.game.pm2.active.module;

import org.joda.time.DateTime;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.acttaskranking;
import yxy.cherry.data.bean.task;
import yxy.game.pm2.active.ActiveUtil;
import yxy.game.pm2.active.module.actcontrol.activeControl;
import yxy.game.pm2.active.module.actdata.ActDataCenter;
import yxy.game.pm2.active.module.rushtoptarget.CBTask;
import yxy.game.pm2.active.module.subordinateclass.rankrush.RankRush;
import yxy.game.pm2.active.module.subordinateclass.rankrush.cbtask;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.bean.db.dao.MySQLCacheDAO;
import yxy.game.pm2.bean.module.AreaModule;
import yxy.game.pm2.bean.module.PlayerModule;
import yxy.game.pm2.bean.module.rank.active.RankRushEnum;
import yxy.game.pm2.bean.task.Task;
import yxy.game.pm2.bean.timeline.Timeline;
import yxy.game.pm2.module.tip.TipHandle;
import yxy.game.pm2.module.tip.TipType;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class ActiveModule_冲榜 extends PlayerModule {

    //bean ----------------------------------------------------
    public static final int acttype = 300;

    private int round;        //轮次
    private int runday;        //进行中天数
    private int runtype;    //进行中冲榜类型
    private HashMap<Integer, CBTask> idtaskcode = new HashMap<Integer, CBTask>();    //进行中冲榜 key : 表格id value ：任务code
    private DateTime runend;        //进行中冲榜结束时间
    private HashMap<Integer, RankRush> rrmap = new HashMap<Integer, RankRush>();    //key : acttype  value : rankrush   旧数据

    public int getRound() {
        return round;
    }

    public void setRound(int round) {
        this.round = round;
    }

    public int getRunday() {
        return runday;
    }

    public void setRunday(int runday) {
        this.runday = runday;
    }

    public int getRuntype() {
        return runtype;
    }

    public void setRuntype(int runtype) {
        this.runtype = runtype;
    }

    public HashMap<Integer, CBTask> getIdtaskcode() {
        return idtaskcode;
    }

    public void setIdtaskcode(HashMap<Integer, CBTask> idtaskcode) {
        this.idtaskcode = idtaskcode;
    }

    public DateTime getRunend() {
        return runend;
    }

    public void setRunend(DateTime runend) {
        this.runend = runend;
    }

    public HashMap<Integer, RankRush> getRrmap() {
        return rrmap;
    }

    public void setRrmap(HashMap<Integer, RankRush> rrmap) {
        this.rrmap = rrmap;
    }

    //func ----------------------------------------------------

    /**
     * @param playercode
     */
    public static ActiveModule_冲榜 create(String playercode) {
        AreaBean ab = AreaModule.area(playercode);//玩家所在区服
        activeControl sai = activeControl.get(ab.getAreaId(), acttype);//去activeControl表拿初始化数据

        if (!sai.running()) {
            return null;
        }

        ActiveModule_冲榜 am = new ActiveModule_冲榜();
        am.setPlayerCode(playercode);
        am.setTimeline(sai.getTimeline());
        am.setRound(0);

        int runday = am.getrunday();//计算循环内的第几天
        int type = am.getruntype(runday);//按天数匹配活动
        if (type == 0) {
            return null;
        }

        am.setRunday(runday);
        am.setRuntype(type);

        DateTime runend = getrunendtime(runday);
        am.setRunend(runend);

        Map<String, acttaskranking> datamap = ActDataCenter.getAllData(acttaskranking.class, playercode);
        for (acttaskranking data : datamap.values()) {
            if (data.getGroup() == type) {
                int taskid = data.getTaskid();
                task taskdata = DataCenter.getData(taskid, task.class);
                if (taskdata == null) {
                    continue;
                }

                Task taskbean = Task.create(playercode, taskdata);
                CBTask ct = new CBTask(data.getId(), taskid, taskbean.getCode());
                am.getIdtaskcode().put(ct.getId(), ct);
            }
        }

        am.set();
        return am;
    }

//	public static final int canget = 1;
//	public static final int hadget = 2;
//	public static final int cannotget = 3;

    /**
     * 获取循环内运行天数
     *
     * @param
     * @return
     */
    private int getrunday() {
        int days = ActiveUtil.days(getTimeline().getStartTime(), DateTime.now());
        int runday = days % 28 + 1;
        return runday;
    }

    private int getround() {
        int days = ActiveUtil.days(getTimeline().getStartTime(), DateTime.now());
        int round = days / 28 + 1;
        return round;
    }

    /**
     * 获取运行冲榜类型
     *
     * @param runday 循环内运行天数
     * @return
     */
    public int getruntype(int runday) {
        if (runday >= 1 && runday <= 7) {
            return RankRushEnum.冲榜_金币兑换.getType();
        }

        if (runday >= 8 && runday <= 14) {
            return RankRushEnum.冲榜_副本关卡.getType();
        }

        if (runday >= 15 && runday <= 21) {
            return RankRushEnum.冲榜_剿匪次数.getType();
        }

        if (runday >= 22 && runday <= 28) {
            return RankRushEnum.冲榜_快速作战.getType();
        }

        return 0;
    }

    /**
     * 计算单个冲榜结束时间
     *
     * @param runday
     * @return
     */
    public static DateTime getrunendtime(int runday) {
        DateTime now = DateTime.now();
        int yu = runday % 7;
        if (yu == 0) {
            DateTime end = now.withHourOfDay(23).withMinuteOfHour(59).withSecondOfMinute(59).withMillisOfSecond(0);
            return end;
        }
        int surplusdays = 7 - yu;
        DateTime end = now.plusDays(surplusdays).withHourOfDay(23).withMinuteOfHour(59).withSecondOfMinute(59).withMillisOfSecond(0);
        return end;
    }


    //更新活动
    public void update() {

        //处理旧数据
        {
            if (getRrmap() != null) {
                ArrayList<String> removetaskcodes = new ArrayList<String>();

                for (RankRush rr : getRrmap().values()) {
                    for (cbtask ct : rr.getIdtaskcodemap().values()) {
                        Task taskbean = Task.get(getPlayerCode(), ct.getTaskcode());
                        if (taskbean == null) {
                            continue;
                        }
                        removetaskcodes.add(taskbean.getCode());
                    }
                }

                Task.remove(getPlayerCode(), removetaskcodes);

                setRrmap(null);
                set();
            }

        }

        //活动
        AreaBean ab = AreaModule.area(getPlayerCode());
        activeControl sai = activeControl.get(ab.getAreaId(), acttype);
        if (sai == null) {
            return;
        }


        //关闭活动
        if (!sai.running() && running()) {
            setTimeline(sai.getTimeline());
            set();
        }

        //开启活动
        if (sai.running() && !running()) {
            reset(getPlayerCode(), sai.getTimeline());
            set();
        }

        //校对开始时间
        if (!sai.getTimeline().getStartTime().isEqual(getTimeline().getStartTime())) {
            setTimeline(sai.getTimeline());
            set();
        }

        //开启 无任务
        if (running()) {
            if (getIdtaskcode() != null && getIdtaskcode().size() != 0) {

            } else {
                reset(getPlayerCode(), sai.getTimeline());
                set();
            }
        }

        if (getRunend() == null) {
            setRunend(getrunendtime(getrunday()));
            set();
        }

        if (getRunend() != getrunendtime(getrunday())) {
            setRunend(getrunendtime(getrunday()));
            set();
        }

        nextruntype();
    }

    /**
     * 核对是否下一个冲榜活动
     */
    private void nextruntype() {
        // 核对活动类型天数
        int runday = getrunday();
        int type = getruntype(runday);

        boolean save = false;

        boolean nextround = false;
        if (getround() != getRound()) {
            setRound(getround());
            save = true;
            nextround = true;
        }

        // 核对天数
        if (runday != getRunday()) {
            setRunday(runday);
            save = true;
        }

        // 核对活动类型
        if (type != getRuntype() || nextround) {
            setRuntype(type);
            setRunend(getrunendtime(getrunday()));

            // 删除上个冲榜任务
            for (CBTask ct : getIdtaskcode().values()) {
                Task.remove(getPlayerCode(), ct.getTaskcode());
            }

            setIdtaskcode(new HashMap<Integer, CBTask>());

            Map<String, acttaskranking> datamap = ActDataCenter.getAllData(acttaskranking.class, getPlayerCode());
            for (acttaskranking data : datamap.values()) {
                if (data.getGroup() == type) {
                    int taskid = data.getTaskid();
                    task taskdata = DataCenter.getData(taskid, task.class);
                    if (taskdata == null) {
                        continue;
                    }

                    Task taskbean = Task.create(getPlayerCode(), taskdata);
                    CBTask ct = new CBTask(data.getId(), taskid, taskbean.getCode());
                    getIdtaskcode().put(ct.getId(), ct);
                }
            }

            save = true;
        }

        if (save) {
            set();
        }

    }

    /**
     * 重置
     * //	 * @param playercode
     *
     * @param tl
     */
    private void reset(String playercode, Timeline tl) {
        //删除上个冲榜任务
        for (CBTask ct : getIdtaskcode().values()) {
            Task.remove(playercode, ct.getTaskcode());
        }

        setTimeline(tl);
        setIdtaskcode(new HashMap<Integer, CBTask>());

        int runday = getrunday();
        int type = getruntype(runday);
        if (type == 0) {
            return;
        }

        setRunday(runday);
        setRuntype(type);

        Map<String, acttaskranking> datamap = ActDataCenter.getAllData(acttaskranking.class, getPlayerCode());
        for (acttaskranking data : datamap.values()) {
            if (data.getGroup() == type) {
                int taskid = data.getTaskid();
                task taskdata = DataCenter.getData(taskid, task.class);
                if (taskdata == null) {
                    continue;
                }

                Task taskbean = Task.create(playercode, taskdata);
                CBTask ct = new CBTask(data.getId(), taskid, taskbean.getCode());
                getIdtaskcode().put(ct.getId(), ct);
            }
        }

        set();
    }

    // redis ---------------------------------------------------------

    static private String key(String playerCode) {
        return String.format("PLAYER:%s:ACTIVE:%S", playerCode, acttype);
    }

    public void set() {
        try {
            String key1 = key(getPlayerCode());
            setv(key1, this);
            check();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取 ActiveModule_冲榜
     *
     * @param playerCode
     * @return
     */
    static public ActiveModule_冲榜 get(String playerCode, Boolean isNewPlayer) {
        try {
            ActiveModule_冲榜 module = getv(key(playerCode));
            if (module == null) {

                //新用户不需要去查数据库
                if (!isNewPlayer) {
                    module = MySQLCacheDAO.getV(key(playerCode), ActiveModule_冲榜.class);
                    if (module != null) {
                        module.set();
                    }//同步到redis
                }

                if (module == null) {
                    module = create(playerCode);
                }
            }

            module.update();
            module.check();
            return module;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查看是否有可领取奖励 控制红点
     */
    public void check() {
        if (running()) {
            new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.开启);
        } else {
            new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.关闭);
        }

        for (int type : RankRushEnum.getSequence()) {
            new ActOpenHandle().updateActOpen(getPlayerCode(), type, type == getRuntype() ? OpenType.开启 : OpenType.关闭);
        }

        TipType tt = getRankRushTypeType(getRuntype());

        if (running()) {
            for (CBTask ct : getIdtaskcode().values()) {
                String taskcode = ct.getTaskcode();
                Task taskbean = Task.get(getPlayerCode(), taskcode);
                if (taskbean == null) {
                    continue;
                }

                if (taskbean.isReward()) {
                    continue;
                }

                if (taskbean.isFinish() && !taskbean.isReward()) {
                    new TipHandle().updateTip(getPlayerCode(), tt, true);
                    return;
                }
            }
        }

        new TipHandle().updateTip(getPlayerCode(), tt, false);
    }

    /**
     * 获取冲榜红点类型
     *
     * @param type
     * @return
     */
    private TipType getRankRushTypeType(int type) {
        if (type == RankRushEnum.冲榜_副本关卡.getType()) {
            return TipType.活动_冲榜副本关卡奖励;
        }

        if (type == RankRushEnum.冲榜_剿匪次数.getType()) {
            return TipType.活动_冲榜剿匪次数奖励;
        }

        if (type == RankRushEnum.冲榜_快速作战.getType()) {
            return TipType.活动_冲榜快速作战奖励;
        }

        if (type == RankRushEnum.冲榜_金币兑换.getType()) {
            return TipType.活动_冲榜金币兑换奖励;
        }

        return null;
    }

    //存储到数据库的方法
    public static void saveToDB(String playerCode) {
        try {
            String key = key(playerCode);
            if (touchBucket(key).isExists()) {
                ActiveModule_冲榜 activeModule_冲榜 = getv(key(playerCode));
                MySQLCacheDAO.setV(key, activeModule_冲榜);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //从redis移走数据的操作
    public static void removeAllFromRedis(String playerCode) {
        try {
            touchBucket(key(playerCode)).delete();
        } catch (RedisException e) {
            e.printStackTrace();
        }
    }
    // lock==========================================================================

    @Override
    public String lockKey() {
        return String.format("lock:%s", key(getPlayerCode()));
    }

}
